import mechanize
import cookielib
import os

import sys, logging
m_logger = logging.getLogger("mechanize")
m_logger.addHandler(logging.StreamHandler(sys.stdout))
m_logger.setLevel(logging.DEBUG)

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.DEBUG)


def do_login(COOKIEFILE,plugin):

    # login page
    url="http://www.amazon.co.uk/gp/flex/sign-out.html"
    
    #if os.path.isfile(COOKIEFILE):
    #    os.remove(COOKIEFILE)
    userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
    cj = cookielib.LWPCookieJar()
    br = mechanize.Browser()
    br.set_cookiejar(cj)
    br.set_handle_robots(False)
    br.addheaders = [('User-agent', userAgent)]
    
    
    login_form = br.open(url)
    #print response.info()
    #print response.geturl()
    
    br.select_form(name="signIn")
    
    br["email"]    = plugin.get_setting("username")
    br["password"] = plugin.get_setting("password")

    response = br.submit()
    
    error_str = "message_error"
    if error_str in response.read():
        #xbmcgui.Dialog().ok('Login Error',error_str)
        logger.error("Login Error")
        return False
    else:
        logger.info("Login Success")
        cj.save(COOKIEFILE, ignore_discard=True, ignore_expires=True)

    br.set_debug_http(True)
    br.set_debug_responses(True)
    br.set_debug_redirects(True)

    url="http://www.amazon.co.uk"
    isprime = br.open(url)
    prime_str = '"isPrime":1'
    if not prime_str in isprime.read():
        #xbmcgui.Dialog().ok('You\'re account is not a Prime account.',error_str)
        logger.error("Prime Error")
        return False

    return True

